package com.icinfo.cloud.provider.common.utils;

import com.icinfo.framework.core.exception.BusinessException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Valid 的手工校验器
 * @author zhangxiaoyan
 */
public class ValidateUtil {
    /**
     * 校验器
     *
     * @param t   参数
     * @param <T> 参数类型
     * @return
     */
    public static <T> Optional<List<String>> valid(T t) {
        Validator validatorFactory = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<T>> errors = validatorFactory.validate(t);
        List<String> collect = errors.stream().map(error -> error.getMessage()).collect(Collectors.toList());
        if (collect.size()==0){
            collect=null;
        }
        return Optional.ofNullable(collect);
    }

    /**
     * 校验器
     * <br/>
     * <code>
     * Optional<String> validErrorOneStr = ValidateUtil.validReturnErrorOne(caseReasonInfoAdjustDto);
     * validErrorOneStr.ifPresent(errorInfo -> {
     *     throw new BusinessException(errorInfo);
     * });
     * </code>
     *
     * @param t   参数
     * @param <T> 参数类型
     * @return 返回校验不通过的第一条记录
     */
    public static <T> Optional<String> validReturnErrorOne(T t) {
        Optional<List<String>> validList = valid(t);
        String errorInfo = null;
        if (validList.isPresent()){
            errorInfo=validList.get().get(0);
        }
        return Optional.ofNullable(errorInfo);
    }

    /**
     * @Valid 的校验器
     * <br/>
     * <code>
     *     ValidateUtil.validThrowException(caseReasonInfoAdjustDto);
     * </code>
     *
     * @param t
     * @param <T>
     * @return 如果校验不通过,直接抛出业务异常
     */
    public static <T> void validThrowException(T t) {
        Optional<List<String>> validList = valid(t);
        if (validList.isPresent()){
            throw new BusinessException(validList.get().get(0));
        }
        
    }
}
